/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: swx  Date: 2019/09/10 Time: 16:03
 *
 * 客房清洁
 */

import React, {Component} from 'react';
import {
    View,
    Text,
    TouchableOpacity,
    TouchableHighlight, ScrollView, SafeAreaView, Image, Modal, ToastAndroid
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from './addLinenAndBarScreen.Style';
import {retrieveLinenAndBar,save_linen,save_bar} from "./Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import LoadingView from "../../../component/LoadingView/LoadingView";
import HS_TouchableHighlight from "../../../hsstyle/HS_TouchableHighlight";
import ScrollableTabView, { DefaultTabBar,ScrollableTabBar } from 'react-native-scrollable-tab-view';
import AntDesign from "react-native-vector-icons/AntDesign";
import Entypo from "react-native-vector-icons/Entypo";
import DividingLineViewComponent from "../../../component/DividingLineViewComponent/DividingLineViewComponent";
import {FONT_COLOR_SUB_TITLE, COLOR_FOCUS,} from "../../../constant/PHColors";



class addLinenAndBarScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: `选择布草/易耗品`,
    });

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            place: this.props.navigation.getParam("place"),
            orderpid: this.props.navigation.getParam("orderpid")?this.props.navigation.getParam("orderpid"):'',
            gno: this.props.navigation.getParam("gno")?this.props.navigation.getParam("gno"):'',
            consume_arr: [],       //易耗品
            linen_arr: [],         //布草
            bar_arr: [],           //酒水（消费项）
            name: '',               //组别分类
            code_chaecked: {"linen": {}, "consume": {}, "bar": {}},      //已选中code  例：{"linen":{"170001":"1","170003":"2"}}
            numModalVisible: false,  //数量模态
            menuVisible: false,      //菜单模态
        };
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        // if (nextProps.onLinenAndBar !== this.props.onLinenAndBar && nextProps.onLinenAndBar.fetchStatus === FetchStatus.Success) {
        //     if (nextProps.onLinenAndBar.RETURN === ReturnStatus.Success) {
        //         let data_source = nextProps.onLinenAndBar.DATA.sort(this.sortnum);
        //         // console.log(JSON.stringify(data_source))
        //         let linen_arr = [];
        //         let consume_arr = [];
        //         let bar_arr = [];
        //         data_source.map((item, index) => {
        //             if (item.hskp_otype === 'CONSUME') {
        //                 consume_arr.push(item)
        //             } else if (item.hskp_otype === 'LINEN') {
        //                 linen_arr.push(item)
        //             } else if (item.hskp_otype === 'BAR') {
        //                 bar_arr.push(item)
        //             }
        //         })
        //
        //         this.setState({
        //             linen_arr: linen_arr,
        //             consume_arr: consume_arr,
        //             bar_arr: bar_arr,
        //         })
        //     } else {
        //         dispatch(doDisplayWarnMessage(nextProps.onLinenAndBar.MSG))
        //     }
        // }

        if (nextProps.onLinen_save !== this.props.onLinen_save && nextProps.onLinen_save.fetchStatus === FetchStatus.Success) {
            if (nextProps.onLinen_save.RETURN === ReturnStatus.Success) {
                ToastAndroid.show(nextProps.onLinen_save.MSG, 500);//提示

                this.props.navigation.state.params.callBack();
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onLinen_save.MSG))
            }
        }

        // if (nextProps.onBar_save !== this.props.onBar_save && nextProps.onBar_save.fetchStatus === FetchStatus.Success) {
        //     if (nextProps.onBar_save.RETURN === ReturnStatus.Success) {
        //         ToastAndroid.show(nextProps.onBar_save.MSG,500);//提示
        //     } else {
        //         dispatch(doDisplayWarnMessage(nextProps.onBar_save.MSG))
        //     }
        // }
    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;
        // dispatch(retrieveLinenAndBar())

        this.props.ondictcode.map((item, index) => {
            let linen_arr = this.state.linen_arr;
            let consume_arr = this.state.consume_arr;
            let bar_arr = this.state.bar_arr;
            if(item.mname==="布草"&&item.level!=='1'){
                linen_arr.push(item)
            }else if(item.mname==="易耗品"&&item.level!=='1'){
                consume_arr.push(item)
            }else if(item.mname==="消费项目"&&item.level!=='1'){
                bar_arr.push(item)
            }
            this.setState({
                linen_arr:linen_arr,
                consume_arr:consume_arr,
                bar_arr:bar_arr,
            })
        })
    }

    render() {
        let {dispatch, onLinenAndBar} = this.props;
        return (
            <SafeAreaView style={styles.body}>
                <ScrollableTabView
                    tabBarUnderlineColor="#4DC5FF"
                    tabBarTextStyle={{
                        fontSize: 18
                    }}
                    tabBarUnderlineStyle={{backgroundColor: '#4C70FF'}}
                    tabBarActiveTextColor="#4C70FF"
                    renderTabBar={() => <DefaultTabBar/>}
                >

                    <View tabLabel='布草' style={styles.container}>
                        <SafeAreaView style={[styles.container, {paddingBottom: 50}]}>
                            <ScrollView style={styles.scrollView}>
                                {
                                    this.state.linen_arr.map((item, index) => {
                                        let menu = "false";
                                        if (item.level==='2') {
                                            menu = "true"
                                        }
                                        this.state.name = item.name;

                                        let check = "false";
                                        if (this.state.code_chaecked.linen[item.code]) {
                                            check = "true"
                                        }
                                        return (
                                            this._render_Item(item, index, menu, check, 'linen')
                                        );

                                    })
                                }
                            </ScrollView>
                        </SafeAreaView>
                    </View>

                    <View tabLabel='易耗品' style={styles.container}>
                        <SafeAreaView style={[styles.container, {paddingBottom: 50}]}>
                            <ScrollView style={styles.scrollView}>
                                {
                                    this.state.consume_arr.map((item, index) => {
                                        let menu = "false";
                                        if (item.level==='2') {
                                            menu = "true"
                                        }
                                        this.state.name = item.name;

                                        let check = "false";
                                        if (this.state.code_chaecked.consume[item.code]) {
                                            check = "true"
                                        }
                                        return (
                                            /*布草循环*/
                                            this._render_Item(item, index, menu, check, 'consume')
                                        );

                                    })
                                }
                            </ScrollView>
                        </SafeAreaView>
                    </View>

                    {/*{
                        (this.state.place.split(",").length<=1)
                        &&
                        (*/}
                            <View tabLabel='消费项' style={styles.container}>
                                <SafeAreaView style={[styles.container, {paddingBottom: 50}]}>
                                    <ScrollView style={styles.scrollView}>
                                        {
                                            this.state.bar_arr.map((item, index) => {
                                                let menu = "false";
                                                if (item.level==='2') {
                                                    menu = "true"
                                                }
                                                this.state.name = item.name;

                                                let check = "false";
                                                if (this.state.code_chaecked.bar[item.code]) {
                                                    check = "true"
                                                }
                                                return (
                                                    /*布草循环*/
                                                    this._render_Item(item, index, menu, check, 'bar')
                                                );

                                            })
                                        }
                                    </ScrollView>
                                </SafeAreaView>
                            </View>
                        {/*)
                    }*/}


                </ScrollableTabView>

                <View style={styles.bodyBottom}>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => {
                        this.setState({
                            menuVisible: true,
                        })
                    }}>
                        <View style={styles.bodyBottomLeft}>
                            <Text style={styles.cellTitleText}>
                                <AntDesign name={'ellipsis1'} size={25} style={{color: 'white'}}/>
                            </Text>
                        </View>
                    </TouchableOpacity>

                    <TouchableOpacity activeOpacity={0.8} onPress={() => this.save()}>
                        <View style={styles.bodyBottomRight}>
                            <Text style={styles.cellTitleText}>
                                完成
                            </Text>
                        </View>
                    </TouchableOpacity>

                </View>

                {/*...菜单*/}
                <Modal visible={this.state.menuVisible} animationType={'none'} transparent={true}
                       onRequestClose={() => this._requestClose()}>
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={() => this._requestClose()}>
                        <View style={styles.modalContainer_menu}>
                            <View style={styles.modalBox}>
                                <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={() => {
                                    this._requestClose()
                                }}>
                                    <View style={styles.modalBottom}>
                                        <Text style={styles.modalTitleText}>
                                            添加备注
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>

                {/*选择数量*/}
                <Modal onRequestClose={() => this._requestClose()} animationType={'none'} transparent={true}
                       visible={this.state.numModalVisible}>
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={() => this._requestClose()}>
                        <View style={styles.modalContainer}>
                            <View style={styles.modalView}>
                                <View style={styles.modalHeader}>
                                    <Text style={styles.modalHeaderText}>
                                        选择数量
                                    </Text>
                                </View>

                                <ScrollView style={styles.scrollView}>
                                    {
                                        this._render_Num()
                                    }
                                </ScrollView>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>
            </SafeAreaView>
        )
    };

    _requestClose() {
        this.setState({
            numModalVisible: false,
            menuVisible: false
        })
    }

    sortnum = (a, b) => {
        return Number(a.code) - Number(b.code);
    };

    //布草循环
    _render_Item = (item, index, menu, check, type) => {
        let _this = this;
        let returnHtml;
        let menuHtml = (
            <View style={styles.cellMenuView}>
                <Text style={styles.cellMenuText}>
                    {item.name}
                </Text>
            </View>
        );
        let itemHtml = (
            <HS_TouchableHighlight key={index} onPress={() => {
                const arr = this.state.code_chaecked;
                if (arr[type][item.code]) {
                    delete arr[type][item.code]
                } else {
                    arr[type][item.code] = "1";
                }
                this.setState({
                    code_chaecked: arr
                });
            }}>
                <View style={styles.boxBody}>
                    <View style={styles.leftBox}>
                        {
                            (check === "true")
                                ?
                                (<AntDesign name={'checkcircle'} size={23} style={{color: COLOR_FOCUS, marginLeft: 10}}/>)
                                :
                                (<Entypo name={'circle'} size={23} style={{color: '#b3b9ba', marginLeft: 10}}/>)
                        }
                        <Text style={styles.leftText}>
                            {item.name}
                        </Text>
                    </View>

                    {
                        (check === "true")
                        &&
                        (
                            <TouchableOpacity style={styles.rightBox} onPress={() => {
                                this.setState({
                                    numModalVisible: !this.state.numModalVisible,
                                })
                                this.selectedType = type;
                                this.selectedcode = item.code;
                            }}>
                                <Text style={styles.rightText}>
                                    数量：
                                </Text>
                                <Text style={styles.numberText}>
                                    {this.state.code_chaecked[type][item.code]}
                                </Text>
                            </TouchableOpacity>
                        )
                    }
                </View>
            </HS_TouchableHighlight>
        );

        if (menu === "true") {
            returnHtml = [menuHtml, itemHtml]
        } else {
            returnHtml = itemHtml
        }

        return returnHtml;
    };

    //循环选择数量模态
    _render_Num = () => {
        let returnhtml;
        let linehtml = (<DividingLineViewComponent lineHeight={1}/>);
        for (let i = 1; i <= 15; i++) {
            this.num = i;
            let font_color = FONT_COLOR_SUB_TITLE;
            if (this.selectedType && this.selectedcode && Number(this.state.code_chaecked[this.selectedType][this.selectedcode]) === i) {
                font_color = COLOR_FOCUS;
            }
            let html = (
                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                    const arr = this.state.code_chaecked;
                    arr[this.selectedType][this.selectedcode] = i;
                    this.setState({
                        code_chaecked: arr,
                        numModalVisible: !this.state.numModalVisible
                    })
                }}>
                    <View style={styles.modalItemView}>
                        <Text style={[styles.modalItemText, {color: font_color}]}>
                            {this.num}
                        </Text>
                    </View>
                </TouchableOpacity>
            );

            returnhtml = [returnhtml, linehtml, html]
        }
        return returnhtml;
    };

    //完成保存
    save=()=>{
        let {dispatch} = this.props;

        if(JSON.stringify(this.state.code_chaecked.linen)!=='{}'||JSON.stringify(this.state.code_chaecked.consume)!=='{}'||JSON.stringify(this.state.code_chaecked.bar)!=='{}'){
            let linen_str = {"arg":{"postgledger":"no"},"whsk_Order_detail":[],"whsk_Order":{"place":this.state.place,"ordertype":"布草/易耗品/酒水补充"}};
            if(this.state.orderpid!==''){
                linen_str.whsk_Order.parentid = this.state.orderpid
            }
            for (let val in this.state.code_chaecked.linen) {
                let json = {"code":val,"quantity":this.state.code_chaecked.linen[val]};
                linen_str.whsk_Order_detail.push(json)
            }
            for (let val in this.state.code_chaecked.consume) {
                let json = {"code":val,"quantity":this.state.code_chaecked.consume[val]};
                linen_str.whsk_Order_detail.push(json)
            }
            for (let val in this.state.code_chaecked.bar) {
                let json = {"code":val,"quantity":this.state.code_chaecked.bar[val]};
                linen_str.whsk_Order_detail.push(json)
            }

            dispatch(save_linen(linen_str))
        }

        // if(JSON.stringify(this.state.code_chaecked.bar)!=='{}'){
        //     let bar_str = {"arg":{},"ho_guest":{},"ho_gledger":[]};
        //     if(this.state.orderpid!==''){
        //         bar_str.arg.orderpid = this.state.orderpid
        //     }
        //     if(this.state.gno!==''){
        //         bar_str.ho_guest.gno = this.state.gno
        //     }
        //     if(this.state.place!==''){
        //         bar_str.ho_guest.room = this.state.place
        //     }
        //     for (let val in this.state.code_chaecked.bar) {
        //         let json = {"ddcode":val,"quantity":this.state.code_chaecked.bar[val]};
        //         bar_str.ho_gledger.push(json)
        //     }
        //     dispatch(save_bar(bar_str))
        // }

    };
}


const props = state => {
    return {
        // onLinenAndBar:state.onLinenAndBar,
        onLinen_save:state.onLinen_save,
        // onBar_save:state.onBar_save,
        ondictcode:state.onCache.dictcode
    }
};

export default addLinenAndBarScreen = connect(props)(addLinenAndBarScreen);
